//Vue.http.options.root = 'http://127.0.0.1:8888';
var keter  =  {
    tokenExpiredBeforeSeconds:60,//token租约续期检查间隔时间
    setItem:function(cname,cvalue,exmin){
      if(window.localStorage){
          window.localStorage.setItem(cname,cvalue);
      }
      else{
          var d = new Date();
          d.setTime(d.getTime()+(exmin*60*1000));
          var expires = "expires="+d.toGMTString();
          document.cookie = cname + "=" + cvalue + "; " + expires;
      }
    }
   ,getItem:function(cname){
     if(window.localStorage){
            return window.localStorage.getItem(cname)
      }
     var name = cname + "=";
     var ca = document.cookie.split(';');
     for(var i=0; i<ca.length; i++)
     {
       var c = ca[i].trim();
       if (c.indexOf(name)==0) return c.substring(name.length,c.length);
     }
     return "";
   }
   ,setToken:function(cvalue){
           this.setItem("token",cvalue);
           if(cvalue){
//               console.log("base64:"+cvalue.split(".")[1]);
               //console.log("token json:"+Base64.decode(cvalue.split(".")[1]));
               //base64解析出来的内容因为结尾有某种特殊字符导致无法通过json解析
              // var obj = JSON.parse(Base64.decode(cvalue.split(".")[1]));
               var str = Base64.decode(cvalue.split(".")[1]);
               var keystr = "expire_seconds";
               var expire_seconds = str.substring(str.indexOf(keystr)+keystr.length+2,str.lastIndexOf("}"));
               //记录token过期时间，用于模拟会话保持
               keter.setItem("token-expired", new Date().getTime()+expire_seconds*1000);
           }
   }
   ,getToken:function(){
     return this.getItem("token");
   }
   ,refreshToken:function(){
       var self = this;
       //alert("vue root:"+Vue.http.options.root);
       Vue.http.get(Vue.http.options.root+'/tokenrefresh', {headers:{'XAuthorization':'Bearer '+self.getToken()}}).then(function (res) {
              keter.setToken(res.data.token);
              console.log("vue token 续费成功！");
       });
   }
   ,tokenExpiredRemainSeconds:function(){
       //计算token到期剩余时间
      return (this.getItem("token-expired")-new Date().getTime())/1000;
   }
   ,get:function (context, url, param) {
          var func = null;
          if (param) {
              func = context.$http.get(context.$http.options.root  + url, {
                  params: param
              });
          } else {
              func = context.$http.get(context.$http.options.root + url);
          }
          return func.then(function (res) {
               return res;
          });
    }
   ,post:function (context, url, param) {
        return context.$http.post(context.$http.options.root + url, param).then(function (res) {
            return res;
        });
    }
   ,handleEx:function (e) {
         if(e.status=='401'){
            alert("认证失败:"+e.statusText+",请登录后访问！");
            window.location.href="/ajax/login";
         }
         else if(e.status=='403'){
            alert("授权失败:"+e.statusText+",请抓紧时间续费！");
         }
    }
}

     if(keter.getToken() &&　keter.tokenExpiredRemainSeconds()<keter.tokenExpiredBeforeSeconds){
//            console.log("token remain seconds:"+keter.tokenExpiredRemainSeconds()+", refresh token");
            keter.refreshToken();
     }

// 错误处理
window.errorInfo = function (errorInfo) {
    alert("我来处理:"+errorInfo);
    var code = errorInfo.code
        , msg = errorInfo.msg
        , result = errorInfo.result;
    return new Promise(function (resolve, reject) {
         resolve(result);
        if (msg != 'error') {
            resolve(result);
        } else {
            reject(result);
        }
    });
}
